package com.freemaster.util;

import java.net.URL;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class CacheUtil {

	private static final String SYS_CACHE ="sysCache";
	//从ApplicationContext获取CacheManager bean.
	private static CacheManager manager =(CacheManager)SpringContextHolder.getBean("cacheManagerFactory");
	
 
	/**
	 * 获取SYS_CACHE缓存
	 * @param key
	 * @return
	 */
	public static Object get(String key){
		return get(SYS_CACHE,key);
	}

	/**
	 * 写入SYS_CACHE缓存
	 * @param key
	 * @param value
	 */
	public static void put(String key ,Object value){
		put(SYS_CACHE,key,value);
	}

	
	/**
	 * 移除缓存
	 * @param key
	 */
	public static  void remove(String key){
		remove(SYS_CACHE,key);
	}
	
	
	/**
	 * 移除全部缓存
	 */
	public static void removeAll(){
		removeAll(SYS_CACHE);
	}
	
	/**
	 * 移除全部缓存
	 * @param sysCache
	 */
	private static void removeAll(String cacheName) {
		getCache(cacheName).removeAll();
		
	}

	/**
	 * 写入缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	private static void put(String cacheName, String key, Object value) {
		Element element =new Element(key,value);
		getCache(cacheName).put(element);
		
	}

	/**
	 *获取缓存
	 * @param sysCache
	 * @param key
	 * @return
	 */
	private static Object get(String cacheName, String key) {
		Element element = getCache(cacheName).get(key);
		return element ==null?null:element.getObjectKey();
	}


	
	/**
	 * 移除缓存
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName,String key){
		getCache(cacheName).remove(key);
	}


	/**
	 * 获得一个Cache ,没有则创建一个
	 * @param cacheName
	 * @return
	 */
	private static Cache getCache(String cacheName) {
		Cache cache = manager.getCache(cacheName);
		if(cache ==null){
			manager.addCache(cacheName);
			cache = manager.getCache(cacheName);
			cache.getCacheConfiguration().setEternal(true);
		}
		return cache;
	}
 
	
	public static CacheManager getCacheManager(){
		return manager;
	}
	
	 
	
}
